package com.dingxin.portal.common.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AntiSQLFilter {

	private static String[] keyWords = { ";", "\"", "\'", "/*", "*/", "--", "%", "=" };

	static boolean isUnsafe(Map parameterMap) {
		Map newMap = new HashMap();
		Iterator iter = parameterMap.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String[] param = (String[]) parameterMap.get(key);
			for (int i = 0; i < param.length; i++) {
				if (isUnsafe(param[i]))
					return true;
			}
		}
		return false;
	}

	static boolean isUnsafe(String value) {
		String lowerCase = value.toLowerCase();
		for (int i = 0; i < keyWords.length; i++) {
			if (lowerCase.indexOf(keyWords[i]) >= 0) {
				return true;
			}
		}
		return false;
	}

	public static Map getSafeParameterMap(Map parameterMap) {
		Map newMap = new HashMap();
		Iterator iter = parameterMap.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String[] oldValues = (String[]) parameterMap.get(key);
			String[] newValues = new String[oldValues.length];
			for (int i = 0; i < oldValues.length; i++) {
				newValues[i] = getSafeValue(oldValues[i].trim());
			}
			if (newValues.length == 1) {
				newMap.put(key, newValues[0]);
			} else {
				newMap.put(key, newValues);
			}
		}
		return Collections.unmodifiableMap(newMap);
	}

	public static String getSafeValue(String oldValue) {
		StringBuffer sb = new StringBuffer(oldValue);
		String lowerCase = oldValue.toLowerCase();
		for (int i = 0; i < keyWords.length; i++) {
			int x = -1;
			while ((x = lowerCase.indexOf(keyWords[i])) >= 0) {
				if (keyWords[i].length() == 1) {
					sb.replace(x, x + 1, " ");
					lowerCase = sb.toString().toLowerCase();
					continue;
				}
				sb.deleteCharAt(x + 1);
				lowerCase = sb.toString().toLowerCase();
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		Map p = new HashMap();
		p.put("aaaa", new String[] { " select " });
		p.put("bbbb", new String[] { "'' select" });
		Map s = getSafeParameterMap(p);
		System.out.println(((String[]) s.get("aaaa"))[0]);
		System.out.println(((String[]) s.get("bbbb"))[0]);
	}
}
